package com.wb.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wb.reggie.common.CustomException;
import com.wb.reggie.entity.Category;
import com.wb.reggie.entity.Dish;
import com.wb.reggie.entity.Setmeal;
import com.wb.reggie.mapper.CategoryMapper;
import com.wb.reggie.service.CategoryService;
import com.wb.reggie.service.DishService;
import com.wb.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        log.info("删除分类，id为：{}",id);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询其记录个数，如果有则说明该分类下有菜品
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int countDish = dishService.count(dishLambdaQueryWrapper);
        log.info("关联{}个菜品",countDish);

        //如果已经关联菜品，抛出一个异常
        if(countDish > 0){
            throw new CustomException("当前分类下关联了菜品，不能删除！");
        }

        //套餐同理
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询其记录个数，如果有则说明该分类下有菜品
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int countSetmeal = setmealService.count(setmealLambdaQueryWrapper);
        log.info("关联{}个套餐",countSetmeal);
        //如果已经关联套餐，抛出一个异常
        if(countSetmeal > 0){
            throw new CustomException("当前分类下关联了套餐，不能删除！");
        }

        //正常删除分类
        super.removeById(id);
    }
}
